package com.jianyun.jyzs.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.jianyun.jyzs.db.DatabaseHelper;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by mlli on 2017/12/12.
 */

public class ModelDao {
    private Dao<ItemModel, Integer> dao;
    private DatabaseHelper dbHelper;

    /**
     * 构造方法
     * 获得数据库帮助类实例，通过传入Class对象得到相应的Dao
     */
    public ModelDao(Context context) {
        try {
            dbHelper = DatabaseHelper.getHelper(context);
            dao = dbHelper.getDao(ItemModel.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void clear(){
        try {
            dao.deleteBuilder().delete();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public void insert(ItemModel itemModel){

        if (getModel(itemModel.getUserId(),itemModel.getEnterpriseCode(),itemModel.getTitle())==null){
            try {
                dao.createOrUpdate(itemModel);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    public void update(ItemModel itemModel){
        try {
            dao.update(itemModel);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public ItemModel getModel(String userId,String enterpriseCode,String title){
        QueryBuilder<ItemModel, Integer> builder = dao.queryBuilder();
        List<ItemModel> list = new ArrayList<>();
        try {
            builder.where().eq("userId",userId).and().eq("enterpriseCode",enterpriseCode).and().eq("title",title);
            list = builder.query();
            if (list.size()>0){
                return list.get(0);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<ItemModel> getModelList(String userId, String enterpriseCode, int i) {
        List<ItemModel> list = new ArrayList<>();
        QueryBuilder<ItemModel, Integer> builder = dao.queryBuilder();
        try {
            builder.where().eq("userId",userId).and().eq("enterpriseCode",enterpriseCode).and().eq("type",i);
            list = builder.query();
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
